package com.ych.modules.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ych.modules.base.dbEntity.RSysRoleMenuEntity;
import com.ych.modules.base.mapper.RSysRoleMenuMapper;
import com.ych.modules.base.service.IRSysRoleMenuService;
import com.ych.utils.MapUtils;
import com.ych.utils.UUID;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/15
 * Time: 15:21
 * Description:
 */
@Service("IRSysRoleMenuService")
public class RSysRoleMenuServiceImpl extends ServiceImpl<RSysRoleMenuMapper, RSysRoleMenuEntity> implements IRSysRoleMenuService {
    @Override
    public List<String> queryMenuIdList(String roleId) {
        Wrapper<RSysRoleMenuEntity> wrapper = new EntityWrapper<RSysRoleMenuEntity>()
                .where("1=1")
                .eq("role_id", roleId)
                .setSqlSelect("menu_id");
        List<Object> list = this.selectObjs(wrapper);
        List<String> strs = null;
        if (null != list && 0 < list.size()) {
            strs = new ArrayList<>();
            for (Object o : list) {
                strs.add((String) o);
            }
        }
        return strs;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveOrUpdate(String roleId, List<String> menuIdList) {
        //先删除角色与菜单关系
        this.deleteBatch(new String[]{roleId});

        if (menuIdList.size() == 0) {
            return;
        }

        //保存角色与菜单关系
        List<RSysRoleMenuEntity> list = new ArrayList<>(menuIdList.size());
        for (String menuId : menuIdList) {
            RSysRoleMenuEntity sysRoleMenuEntity = new RSysRoleMenuEntity();
            sysRoleMenuEntity.setRoleMenuId(UUID.randomUUID());
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);
            list.add(sysRoleMenuEntity);
        }
        this.insertBatch(list);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int deleteBatch(String[] roleIds) {
        for (String roleId : roleIds) {
            this.deleteByMap(new MapUtils().put("role_id", roleId));
        }
        return 0;
    }
}
